package com.westar.core.services;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.westar.base.businessUtil.EditAffairUtil;
import com.westar.base.businessUtil.NextTaskInfoUtil;
import com.westar.base.businessUtil.ViewTaskUtil;
import com.westar.base.emum.PublicServiceEnum;
import com.westar.base.exceptions.AffariBusinessException;
import com.westar.base.exceptions.ValidateException;
import com.westar.base.model.AffairInfo;
import com.westar.base.model.ImplementDetail;
import com.westar.base.model.UserInfo;
import com.westar.base.pojo.Affair;
import com.westar.base.pojo.WestarResult;
import com.westar.base.util.DateTimeUtil;
import com.westar.base.util.WestarHttpUtil;
import com.westar.base.validateutil.ValidateEditAffair;
import com.westar.core.conf.SysConst;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 现场申请的Service
 */
@Service
public class AffairEditService {

    private static Logger logger = LoggerFactory.getLogger( AffairEditService.class);

    @Autowired
    private ImplementService implementService;

    @Autowired
    private AffairInfoService affairInfoService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SystemLogService systemLogService;

    @Autowired
    private Environment env;

    /**
     * 添加现场申请一条数据
     * @param actCookie 唯一标识
     * @param affair 参数
     * @param sessionUser
     */
    public WestarResult addAffair(String actCookie, Affair affair, UserInfo sessionUser, MultiValueMap<String, MultipartFile> multipartFile)
            throws IOException, AffariBusinessException{
        //字段校验
        try {
            ValidateEditAffair.checkForAddAffair(affair);
        } catch (ValidateException e) {
            return WestarResult.build( -1,e.getMsg());
        }

        //字段解析成map
        Gson gson = new Gson();
        JSONObject jsonObject = JSONObject.parseObject(gson.toJson(affair));
        Map<String,String>  params =  new HashMap<String,String>(30 );
        Iterator itor = jsonObject.entrySet().iterator();
        while (itor.hasNext()){
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) itor.next();
            String key = entry.getKey();
            if (Objects.nonNull(entry.getValue())) {
                String value = entry.getValue().toString();
                params.put(key,value);
            }
        }

        //事项编码
        String eventCode = params.get("eventCode");
        //事项名称
        String eventName = params.get("affairName");
        if(StringUtils.isEmpty( eventCode ) && StringUtils.isEmpty( eventName )){
            throw new AffariBusinessException(-1,"事项编码或事项名称：不能为空！","");
        }
        //获取事项详情
        ImplementDetail implementDetail = this.getImplementDetail(actCookie, affair, sessionUser);

        //构建隐藏字段信息
        Map<String,String> appendHiddenParam = new HashMap<String,String>(  );
        appendHiddenParam.put( "appoveObject",implementDetail.getAppoveObject() );
        appendHiddenParam.put( "eventName",implementDetail.getEventName() );
        appendHiddenParam.put( "promiseTimeLimit",implementDetail.getPromiseTimeLimit() );
        appendHiddenParam.put( "legalTimeLimit",implementDetail.getLegalTimeLimit() );
        appendHiddenParam.put( "majorTerm",implementDetail.getMajorTerm() );
        appendHiddenParam.put( "implListId",implementDetail.getImplListId() );

        //构建查询事项模板信息的参数
        Map<String,String> searchParamForWfTemplate = new HashMap<>();
        searchParamForWfTemplate.put( "implListId",implementDetail.getImplListId());
        searchParamForWfTemplate.put( "implWfStatus","2");
        //查询并校验模板
        Map<String,String> queryAndValidWfTemplate = EditAffairUtil.queryAndValidWfTemplate(actCookie,searchParamForWfTemplate,"1");
        if(null != queryAndValidWfTemplate && !queryAndValidWfTemplate.isEmpty()){
            appendHiddenParam.putAll(queryAndValidWfTemplate);
        }else{
            systemLogService.addSystemLog(sessionUser.getAccount(),"-","-1","事项编码："+eventCode+"，在一体化平台校验模板失败！");
            throw new AffariBusinessException(-1,"事项编码：%s，在一体化平台校验模板失败！",eventCode);
        }

        params.putAll(appendHiddenParam);

        //默认保存类型为0
        String saveType = "0";
        //默认保存主键为0
        String id="0";

        //获取填写数据的页面
        String pageInfo= EditAffairUtil.affairEditRespone(actCookie,id,"1","0");

        Document document = Jsoup.parse(pageInfo);
        Elements eleForm = document.select("#cc");
        Elements formDatas = eleForm.select( "div[title='基本信息']" );

        //构建需要保存的数据
        Map<String,String> result = EditAffairUtil.contrFormDataForFirstSave(saveType,pageInfo,params);

        //除开遂宁，其他项目需要传递照片
        if(StringUtils.isEmpty(SysConst.ITEM_NAME) || !"suining".equals(SysConst.ITEM_NAME)){
            //构建照片信息
            String applicantPhotoId = EditAffairUtil.constrApplicantPhotoId(actCookie,pageInfo,multipartFile,params);
            if(StringUtils.isNotEmpty( applicantPhotoId )){
                result.put("applicantPhotoId",applicantPhotoId);
            }
        }

        //暂存
        WestarResult westarResult = EditAffairUtil.affairEdit(actCookie,document,result,saveType,id);

        if(westarResult.getStatus() == 0){
            //暂存成功后返回事项主键
            String affairId = westarResult.getData().toString();
            //将事项主键保存到数据库
            affairInfoService.addAffairInfo(sessionUser,affairId);

            //根据主键查询事项编码
            String pageEditInfo= EditAffairUtil.affairEditRespone(actCookie,affairId,null,null);
            Document docEdit = Jsoup.parse(pageEditInfo);

            String affairCode = docEdit.select("input[name='affairCode']").attr("value");
            affairInfoService.updateAffairCodeAndHandTime(affairId ,affairCode,sessionUser.getAccount() );

            //添加日志
            systemLogService.addSystemLog(sessionUser.getAccount(),affairCode,"0","添加现场申请一条数据成功！编码："+affairCode);

            westarResult.setData(affairCode);
            return westarResult;
        }else{
            //添加日志
            systemLogService.addSystemLog(sessionUser.getAccount(),"-","-1","添加现场申请一条数据失败！");
        }
        return westarResult;
    }

    /**
     * 获取事项详情
     * @param actCookie
     * @param affair
     * @param sessionUser
     * @return
     * @throws AffariBusinessException
     * @throws IOException
     */
    private ImplementDetail getImplementDetail(String actCookie, Affair affair, UserInfo sessionUser) throws AffariBusinessException, IOException {

        String eventCode = affair.getEventCode();
        String eventName = affair.getEventName();
        //查询的事项
        String isNotPublicServices = affair.getIsNotPublicServices();
        if(StringUtils.isEmpty(isNotPublicServices)){
            isNotPublicServices = PublicServiceEnum.POWER.getParam();
        }


        List<Map<String, String>> mapList = PublicServiceEnum.toList();

        //用当前账号取得实施事项详情信息
        ImplementDetail implementDetail = implementService.getImplementDetailFromUp(eventCode,eventName,actCookie,sessionUser.getAreaCode(),isNotPublicServices);
        if(null == implementDetail){
            //用当前账号取得实施事项详情信息【其他模块】
            for(Map<String, String> subMap : mapList){
                String subisNotPublicServices = subMap.keySet().iterator().next();
                if(subisNotPublicServices.equals(isNotPublicServices)){
                    continue;
                }
                implementDetail = implementService.getImplementDetailFromUp(eventCode,eventName,actCookie,sessionUser.getAreaCode(),subisNotPublicServices);
                if(null != implementDetail){
                    break;
                }

            }

        }

        //用管理员账号取得实施事项详情信息
        if(null == implementDetail){
            //用管理员账号取得实施事项详情信息
            implementDetail = implementService.getImplementDetailFromUpByAdmin(eventCode,sessionUser.getAreaCode(),isNotPublicServices);
            //用当前账号取得实施事项详情信息【其他模块】
            for(Map<String, String> subMap : mapList){
                String subisNotPublicServices = subMap.keySet().iterator().next();
                if(subisNotPublicServices.equals(isNotPublicServices)){
                    continue;
                }
                implementDetail = implementService.getImplementDetailFromUpByAdmin(eventCode,sessionUser.getAreaCode(),subisNotPublicServices);
                if(null != implementDetail){
                    break;
                }
            }
        }

        if(null == implementDetail){
            //添加日志
            systemLogService.addSystemLog(sessionUser.getAccount(),"-","-1","事项编码："+eventCode+"，在一体化平台不存在！");
            throw new AffariBusinessException(-1,"事项编码：%s，在一体化平台不存在！",eventCode);
        }else{
            //授权状态
            boolean authState = EditAffairUtil.checkImplementDetail(actCookie,implementDetail.getEventName(),null);
            //未授权则说明情况
            if(!authState){
                //添加日志
                systemLogService.addSystemLog(sessionUser.getAccount(),"-","-1","事项编码："+eventCode+"，在一体化平台无权限！");

                throw new AffariBusinessException(-1,"事项编码：%s，在一体化平台无权限！",eventCode);
            }
        }
        return implementDetail;
    }

    /**
     * 开始提交审批事项
     * @param actCookie 唯一标识
     * @param affairId 办件主键
     * @param account 当前办理人员
     */
    public WestarResult editAffairEdit(String actCookie,String affairId,String account) {
        String affairCode = null;
        try {
            String pageInfo= EditAffairUtil.affairEditRespone(actCookie,affairId,null,null);
            Document document = Jsoup.parse(pageInfo);
            //修改获取数据的div
            Elements formDataExists = document.select("#data_div");
            String status = formDataExists.select( "#status" ).attr( "value" );
            //应交材料 是否只读
            if(StringUtils.isNotEmpty(status ) && status.equals( "0" )){
                //除开遂宁，其他项目需要传递照片
                String filebasePath = env.getProperty("dataexchange.filebase_path");
                //应交材料（除开遂宁之外，其他需要传附件信息）
                EditAffairUtil.initMaterial(affairId,pageInfo,actCookie,SysConst.ITEM_NAME,filebasePath);
            }
            //构建需要保存的数据
            Map<String,String>  params = EditAffairUtil.constrFormForSave(document ,"4" );

            WestarResult westarResult = EditAffairUtil.affairEdit(actCookie,document,params,"4",affairId);
            if(westarResult.getStatus() == 0){
                westarResult.setData(affairCode);
            }
            return westarResult;
        } catch (Exception e) {
            return WestarResult.build(-1,"error","受理数据，提交表单失败！");
        }
    }

    public WestarResult noaccept(String actCookie,String affairId,String account) {
        //TODO
        return  WestarResult.build(-1,"error","该方法未实现");
    }

    /**
     * 办理任务
     * @param actCookie
     * @param viewTaskParam
     * @param fisrtHandleAccount 办件受理人员
     * @return
     */
    public WestarResult updateHandTask(String actCookie, Map<String, String> viewTaskParam,String fisrtHandleAccount,boolean fromTodo,String affairCode) throws Exception {
        String wfTaskId = viewTaskParam.get("taskId");

        Map<String, String> preSearchParam = new HashMap<>();
        preSearchParam.put( "procInstId",viewTaskParam.get("procInstId") );
        preSearchParam.put( "busiId",viewTaskParam.get("busiId"));
        preSearchParam.put( "nodeId",viewTaskParam.get("nodeId"));

        String busiAlias = viewTaskParam.get("busiAlias");
        if(busiAlias.equals( "SCENE")){// 场景办件
            String pageInfo= ViewTaskUtil.viewCdSceneTaskPage(actCookie,wfTaskId,preSearchParam);
            return WestarResult.build( -1,"场景办件此业务未实现" );
        }else{
            if(!fromTodo){//不是从代办中查询的数据
                preSearchParam = null;
            }else{
                preSearchParam.remove("executor");

            }
            String procTaskId = viewTaskParam.get("procTaskId");
            String pageInfo= ViewTaskUtil.viewAffairTaskPage(actCookie,wfTaskId,procTaskId,preSearchParam);
            Document document = Jsoup.parse(pageInfo);
            Elements scripts = document.select("script");

            Elements eleForm = document.select("#affair_tab");

            for(Element script : scripts){
                if(script.html().contains("var taskId_ =")) { //注意这里一定是html(), 而不是text()
                    Map<String,String> searchParam = ViewTaskUtil.getSearchParamForViewTask(script.html());
                    String submitType = null;

                    //受理
                    Elements btn = eleForm.select( "#btn_sl" );
                    //审查
                    Elements decideBtn = eleForm.select( "#decideBtn" );

                    if(null != btn && !btn.isEmpty()){
                        submitType = "1";
                    }else if(null != decideBtn && !decideBtn.isEmpty()){
                        submitType = "8";
                    }else {
                        //制作结束
                        Elements endBtn = eleForm.select( "button" );
                        for(Element ele : endBtn){
                            String onclick = ele.attr( "onclick" );
                            if(onclick.startsWith( "getNextNodeInfo" )){
                                if(onclick.indexOf( "9" )>=0){
                                    //制作证件
                                    submitType = "9";
                                    break;
                                }
                            }else if(onclick.startsWith( "beforeTrunOnNext" )){
                                submitType = "7";
                                break;
                            }else if(onclick.startsWith( "submitTask" )){
                                if(onclick.indexOf( "10" )>=0){
                                    //办结
                                    submitType = "10";
                                    break;
                                }else if(onclick.indexOf( "submitTask()" ) >= 0){
                                    submitType = "";
                                    break;
                                }
                            }else if(onclick.startsWith( "beforeMakeCard" )){
                                if(onclick.indexOf( "9" )>=0){
                                    submitType = "9";

                                    String thingType = eleForm.select("#eventType").attr("value");
                                    if(thingType.equals("1A")){
                                        //查询办理信息
                                        AffairInfo affairInfo = affairInfoService.getAffairInfoByCode(affairCode);
                                        //许可有效期开始时间
                                        String licenseStartTime = affairInfo.getPermissionSdate();
                                        if(StringUtils.isEmpty(licenseStartTime)){
                                            licenseStartTime = DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd);
                                        }

                                        //许可有效期结束时间
                                        String licenseEndTime = affairInfo.getPermissionEdate();
                                        if(StringUtils.isEmpty(licenseEndTime)){
                                            licenseEndTime = "2099-12-31";
                                        }
                                        //行政许可决定文书名称
                                        String licenseDocumentsNeme = affairInfo.getPermissionDecideDocName();
                                        if(StringUtils.isEmpty(licenseDocumentsNeme)){
                                            licenseDocumentsNeme = "";
                                        }
                                        //文书号
                                        String licenseDocumentsCode = affairInfo.getPermissionDocNo();
                                        if(StringUtils.isEmpty(licenseDocumentsCode)){
                                            licenseDocumentsCode = "";
                                        }
                                        //许可类别 0:普通  1:特许 2:认可 3:核准 4:登记 5:其他
                                        String licenseTypes = affairInfo.getPermissionCategory();
                                        if(StringUtils.isEmpty(licenseTypes)){
                                            licenseTypes = "5";
                                        }
                                        //说明
                                        String licenseRemark = affairInfo.getPermissionExplain();
                                        if(StringUtils.isEmpty(licenseRemark)){
                                            licenseRemark = "";
                                        }
                                        //行政许可证书名称
                                        String licenseCertificateNeme = affairInfo.getPermissionName();
                                        if(StringUtils.isEmpty(licenseCertificateNeme)){
                                            licenseCertificateNeme = "";
                                        }
                                        //行政许可证书编号
                                        String licenseCertificateCode =affairInfo.getPermissionNo();
                                        if(StringUtils.isEmpty(licenseCertificateCode)){
                                            licenseCertificateCode = "";
                                        }
                                        //开始赋值
                                        document.select( "#licenseStartTime" ).attr( "value" ,licenseStartTime );
                                        document.select( "#licenseEndTime" ).attr( "value" ,licenseEndTime);
                                        document.select( "#handle input[id='licenseDocumentsNeme']" ).attr( "value" ,licenseDocumentsNeme);
                                        document.select( "#handle input[id='licenseDocumentsCode']" ).attr( "value" ,licenseDocumentsCode);
                                        document.select( "#licenseTypes" ).attr( "value" ,licenseTypes);
                                        document.select( "#handle input[id='licenseRemark']" ).attr( "value",licenseRemark );
                                        document.select( "#handle input[id='licenseCertificateNeme']" ).attr( "value" ,licenseCertificateNeme);
                                        document.select( "#handle input[id='licenseCertificateCode']" ).attr( "value",licenseCertificateCode );

                                        pageInfo = document.outerHtml();
                                    }
                                    break;
                                }else if(onclick.indexOf( "3" )>=0){
                                    submitType = "3";
                                    break;
                                }

                            }
                        }
                    }

                    if(null != submitType){
                        if(submitType.equals( "10" ) || submitType.equals( "" )){
                            //许可有效期开始时间
                            String createTime = DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd_HH_mm_ss);

                            //开始赋值
                            document.select( "#createTime" ).attr( "value" ,createTime );

                            pageInfo = document.outerHtml();
                            //办结
                            ViewTaskUtil.submitTask( actCookie,submitType,pageInfo );
                            return WestarResult.ok("finish");
                        }else{
                            //案件提交
                            String nextNodeInfoPage = ViewTaskUtil.getNextNodeInfo(actCookie,searchParam,submitType);
                            NextTaskInfoUtil.jiexiPage(actCookie,nextNodeInfoPage,pageInfo,fisrtHandleAccount);
                            return WestarResult.ok("next");
                        }
                    }
                    break;

                }
            }
        }
        return null;
    }
    /**
     * 修改办件状态
     * @param affairInfo 办件主键
     * @param perFinishState
     */
    public WestarResult updateAffairFinishState(AffairInfo affairInfo, String perFinishState) {
        WestarResult westarResult = affairInfoService.updateAffairFinishState(affairInfo, perFinishState);
        return westarResult;
    }

    /**
     * 构建下一步的办理人信息
     * @param actCookie
     * @param affairCode
     * @param account
     * @return
     */
    public WestarResult constrViewDoneTaskParam(String actCookie, String affairCode, String account) {
        try {
            Map<String, String> viewTaskParam = WestarHttpUtil.constrViewDoneTaskParam(actCookie, affairCode, account);
            if(null == viewTaskParam){
                return null;
            }
            String transactor = viewTaskParam.get("transactor");
            if(StringUtils.isNotEmpty(transactor)){

                List<UserInfo> allChooseUser = userInfoService.listAllOperator(transactor,account);
                if(null==allChooseUser || allChooseUser.isEmpty()){
                    return WestarResult.build(-1,"候选人["+transactor+"]在系统里面没有对应人员");
                }else{
                    String candateUser = null;
                    //默认不包含自己
                    boolean flag = false;
                    for(UserInfo chooseUser: allChooseUser){
                        String chooseAccount = chooseUser.getAccount();
                        if(chooseAccount.equals(account)){
                            flag = true;
                            break;
                        }else if(!chooseUser.getPasswd().equals("-")){
                            if(StringUtils.isEmpty(candateUser)){
                                candateUser = chooseAccount;
                            }
                        }
                    }
                    if(flag){
                        //自己是办理人
                        return WestarResult.ok(account);
                    }else {
                        //有一个默认候选人
                        if(StringUtils.isNotEmpty(candateUser)){
                            return WestarResult.ok(candateUser);
                        }else{
                            return WestarResult.build(-1,"候选人["+transactor+"]在系统里面密码未设定");
                        }
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
